# 计算1-100求和
# sum_1=0
# for i in range(1,101):
#    sum_1=sum_1+i
# print(sum_1)

# 加入分支实现1-100之间的偶数和
# sum_2=0
# for i in range(1,101):
# if i%2==0:
# sum_2=sum_2+i
# print(sum_2)
# 使用Python实现1-100之间偶数求和
# sum_2=0
# for i in range(2,101,2):
# sum_2=sum_2+i
# print(sum_2)

# 猜数字游戏
# import random
# computer=random.randint(1,101)
# while True:
#     preson = int(input("请输入一个整数:"))
#     if preson<computer:
#             print("小了")
#     elif preson>computer:
#             print("大了")
#     elif preson == computer:
#         print("猜对了")
#         break

# 列表：
# list.append(x):在列表末尾添加元素
# list.insert(1,x):在给定的位置添加一个元素
# list.remove(x):移除列表中第一个元素
# list.pop([i]):删除列表中定位的元素并返回它，如果没有给默认删除最后一个元素并返回它
# list.sort(key=None,reverse=False):对列表中的元素进行排序
# list.reverse():反转列表中的元素
# 例子：
# list_1=[]
# for i in range(5):
#     list_1.append(i*2)
# print(list_1)
# list_1=[]
# list_1.extend(i**2 for i in range(5))
# print(list_1)

# ！！！注意
# append只能添加一个元素，打印结果是一个生成器
# list_1=[]
# list_1.append(i**2 for i in range(5))
# print(list_1)
# ！！！

# 列表生成式：
# list_result2=[i*2 for i in range(1,5)]
# print(list_result2)

# 带if条件
# list_result=[]
# for i in range(5):
#     if i != 1:
#         list_result.append(i*2)
# print(list_result)

# list_result2=[i**2 for i in range(5) if i != 1]
# print(list_result2 )

# 嵌套循环
# list_result3=[]
# for i in range(1,4):
#     for j in range(1,4):
#         list_result3.append(i*j)
# print(list_result3 )
# list_result3=[i*j for i in range(1,4) for j in range(1,4)]
# print(list_result3)

# 元组定义，元组不可变
# tuple_result=(1,2,3)
# tuple_result[0]="a"
# print(tuple_result)

# a=[4,5,6]
# tuple_result1=(1,2,a)
# tuple_result1[2][0]=("aa")
# print(tuple_result1)

# a=(1,2,3,4,4,5,6)
# print(a.count(4))  #统计
# print(a.index(2))  #索引
# print(a.index(4))  #重复取第一个索引位置

# 集合：不重复元素组成的无序的集，创建一个空集合只能用set()，不能用{}
# set_1={1,4,5}
# set_2={1,2,3,4,2}
# print(set_1.union(set_2))  #并集
# print(set_1.intersection(set_2))  #交集
# print(set_1.difference(set_2))    #差集
# print(set(set_2))  #去重

# 字典：以关键字作为索引
# dict_1={"a":1,"b":2}  #key值不能是变量
# dict_2=dict(c=3,d=4)
# print(dict_1)
# print(dict_2)
# print(dict_1.keys())
# print(dict_2.values())
# print(dict_1.pop("a"))   #删除键值对
# print(dict_1)
# print(dict_2.popitem()) #随机删除并返回删除的值

# dict_3={}
# dict_4=dict_3.fromkeys({1,2,3},"y")  #fromkeys传入键，再赋值
# print(dict_4)

# 字典推导式
# print({i:i**2 for i in range(1,4)})

# 模块
# 模块导入
# import 模块名
# from <模块名> import <方法/变类/量>
# from <模块名> import *
#  import sys
# import os
# import re
# import json
# import time
# print(dir())
# print(sys.path)

# 字面插值
# 1.格式化输出
# %d：输出整数
# %s：输出字符串
# %f：输出浮点型 ，.2f:表示输出2位小数
# name="python"
# age=3
# print("my name is %s my age is %d my class is %.2f"%(name,age,3.14159))

# 2.format方法
# name="python"
# age=3
# list1=[1,2,3]
# dict1={"name":"tom","age":3}
# print("my name is {0} my age is {1}".format(name,age))
# print("list is {},dict is {}".format(list1,dict1))

# 传入列表、字典中的部分 ,需要解包
# list1=[1,2,3]
# dict1={"name":"tom","age":3}
# print("my class is {}、{} ang {}".format(*list1))
# print("my name is {name} my age is {age}".format(**dict1 ))

# 3. F-strings,字符串格式化机制，支持3.6版本以上
# name="jinjin"
# age=3
# list1=[1,2,3]
# dict1={"name":"tom","age":3}
# print(f'my name is {name} my age is {age}')
# print(f'my class is {list1[1]} my dict is {dict1["name"]}')
# print(f'my name is {name.upper()}')
# print(f"result is {(lambda x:x+1)(2)}")

# 文件读取,r只读，w写入，a追加，buffering=0/1,0不寄存，1寄存区缓存，encoding=utf-8编辑器语言
# 读取图片使用rb，二进制的读取格式，其他文本使用rt
# with open(文件名,打开方式) as f:
# f=open('e:\\a.txt')
# print(f.readable())   #是否可读
# print(f.readline())   #按行读取
# print(f.readlines())  #全部读取
# f.close()             #关闭文件
# 例子
# with open('e:\\a.txt','r') as f:
#     while True:
#         line=f.readline()
#         if line:
#             print(line)
#         else:
#             break

# json格式转换

# import json
# data={
#     "name":["jemer","tom"],
#     "age":28,
#     "gender":"famele"
# }
# data1=json.dumps(data)   #dumps转换为字符串
# print(data1)
# print(type(data1))
# data2=json.loads(data1)   #loads转换为json格式
# print(data2)
# print(type(data2))

# 异常处理
# try...except
# ZeroDivisionError
# try:
#     num1=int(input("请输入一个除数:"))
#     num2=int(input("请输入一个被除数:"))
#     print(num1/num2)
# except ZeroDivisionError:
#     print("被除数等于0")

# ValueError
# try:
#     num1=int(input("请输入一个除数:"))
#     num2=int(input("请输入一个被除数:"))
#     print(num1/num2)
# except ValueError:
#     print("输入的值为数值型")

# try...except...else
# try:
#     num1=int(input("请输入一个除数:"))
#     num2=int(input("请输入一个被除数:"))
#     print(num1/num2)
# except:
#     print("这是一个异常")
# else:
#     print("没有发生异常")

# try...except...finally
# try:
#     num1=int(input("请输入一个除数:"))
#     num2=int(input("请输入一个被除数:"))
#     print(num1/num2)
# except:
#     print("这是一个异常")
# finally:
#     print("无论是否发生异常都执行")

# 类：
# class Person:
#     #在类里定义的变量叫类变量
#     name = "hogwarts"
#     age = 0
#     gender = "男"
#     weigth = 0
#     def __init__(self,name,age,gender,weigth):
#         #在self.变量名的方式定义变量叫实例变量
#         self.name=name
#         self.age=age
#         self.gender=gender
#         self.weigth=weigth
#         print(self.name,self.age,self.gender,self.weigth)
#     @classmethod
#     def set_pram(self):
#         print(f"{self.name} eating")
#     def set_jump(self):
#         print(f"{self.name} jumping")
#     def set_paly(self):
#         print(f"{self.name} palying")
#
# zs=Person("zhangsan","25","男",125)
# print(zs)
# zs.set_jump()
# zs.set_pram()
# zs.set_paly()

# 类变量和实例变量的区别
# 类变量是通过类来访问的，实例变量是通过实例来访问
# print(Person.name)
# zs=Person("zhangsan","25","男",125)
# print(zs.name)

# 类变量和实例变量都是可以修改的
# Person.name="Tom"
# print(Person.name)
# zs.name="lisi"
# print(zs.name)

# 类方法和实例方法的无别
# 类方法是不能访问实例方法,要实现类访问实例方法，可以增加一个装饰器@classmethod
# Person.set_pram()


# OS模块
# import os
# os.mkdir("testdir")                  #创建文件
# print(os.listdir("./"))              #列出文件
# print(os.removedirs("testdir"))      #删除文件
# print(os.listdir("./"))
# print(os.getcwd())                   #获取路径
# print(os.path.exists("b"))            #判断文件是否存在
# if not os.path.exists("b"):
#     os.mkdir("b")
#     if not os.path.exists("b/test.txt"):
#         f=open("b/test.txt","w")
#         f.write("hello,OS is good")
#         f.close()

# time模块
# import time
# print(time.asctime())
# print(time.time())
# print(time.localtime())
# print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))

# 获取两天前的时间
# now_timetamp=time.time()
# two_day_before=now_timetamp-60*60*24*3
# time_tuple=time.localtime(two_day_before)
# print(time.strftime("%Y-%m-%d %H:%M:%S",time_tuple))

# urllib库
# import urllib.request
# response=urllib.request.urlopen("http://www.baidu.com")
# print(response.status)
# print(response.read())
# print(response.headers)

# math库 科学计算方法
# import math
# print(math.ceil(5.5))     #返回等于等于x的最小整数
# print(math.floor(5.5))    #返回小于等于x的最大整数
# print(math.sqrt(36))      #开方根


# 多线程和多进程
# GIL同一时刻只有一个线程在执行
# import threading
# import time
#
# def task1():
#     time.sleep(5)
#     print("扔第二个苹果")
# def task2():
#     print("扔第三个苹果")
#
# def main():
#     start_time=time.time
#     # threading.Thread创建一个线程
#     thread1=threading.Thread(target=task1)
#     thread2=threading.Thread(target=task2)
#     # 执行线程
#     thread1.start()
#     thread2.start()
#     # 让其他线程执行完成
#     thread1.join()
#     thread2.join()
#
#     end_time=time.time()
#     print("执行线程使用时间:",end_time-start_time)
#     print("扔第一个苹果")
#
# if __name__=="main":
#     main()


# 对外部数据进行处理
# YAML:可读性高，用来表达数据序列化的格式
# JSON:一个轻量级的数据交换语言,用来传输属性值或者序列性的值组成的数据对象
# EXCEL:有直观界面、出色的计算机功能和图表工具是一款电子指标软件

# 创建表格和工作表
# from openpyxl import Workbook
# from openpyxl.utils import get_column_letter
#
# wb = Workbook()
#
# dest_filename = 'empty_book.xlsx'
#
# ws1 = wb.active
# ws1.title = "range names"
#
# for row in range(1, 40):
#     ws1.append(range(600))
#
# ws2 = wb.create_sheet(title="Pi")
#
# ws2['F5'] = 3.14
#
# ws3 = wb.create_sheet(title="Data")
# for row in range(10, 20):
#
#     for col in range(27, 54):
#         ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))
#
# ws4=wb.create_sheet(title="my_sheel")
# for i in range(1,11):
#     ws4.cell(column=1,row=i).value="test"
#
# print(ws3['AA10'].value)
# print(ws4['A1'].value)
# wb.save(filename=dest_filename)

# 读取excel内容
# from openpyxl import load_workbook
# wb = load_workbook(filename='empty_book.xlsx')
# sheet_ranges = wb['range names']
# print(sheet_ranges['D18'].value)
# for i in range(1,31):
#     print(sheet_ranges.cell(column=1,row=i).value)

# YAML读写
import yaml
#转换列表格式
# print(yaml.load("""
# - Hesperiidae
# - Papilionidae
# - Apatelodidae
# - Epiplemidae
# """))
# print(yaml.load("""
# - Hesperiidae
# - Papilionidae
# - Apatelodidae
# - Epiplemidae
# """,Loader=yaml.FullLoader))

#转换字典格式
# print(yaml.load("""
# a: 1
# """,Loader=yaml.FullLoader))

#格式嵌套
# print(yaml.load("""
# -
#     - Hesperiidae
#     - Papilionidae
# -
#     - Apatelodidae
#     - Epiplemidae
#     - a: 1
# """,Loader=yaml.FullLoader))

# 读取yaml文件,yaml.load将yaml格式转换为列表、字典
# print(yaml.load(open("./demo.yaml"),Loader=yaml.FullLoader))
# yaml.dump将yaml格式转换为列表、字典
# print(yaml.dump({'a': [1, 2]}))
# with open("./demo2.yaml","w") as f:
#     yaml.dump(data={'a': [1, 2]},stream=f)

# 实战例子1
# 第一个类Bicycle(自行车)
    # run()方法，打印骑行公里数
# 第二个类EBycycle继承自Bycycle
    # volume(电量)属性
    # fill_charge充电方法
    # run()方法用于骑行，没骑行10km消耗一度电，当电量消耗进调用Bycycle的run()方法骑行，通过传入的骑行里程数，显示骑行结束
# class Bike:
#     def run(self,vol):
#         """
#         :param vol: 骑行的公里数
#         """
#         print(f"自动骑行的公里数为{vol}")
#
# class EBike(Bike):
#     volume=10
#     def fill_charge(self,vol):
#         """
#         :param vol: 充电电量
#         :return:
#         """
#         # 如果在方法内调用类变量，使用self.进行获取
#         self.volume=self.volume+vol
#         print(f"充电之后的电量为{self.volume}")
#
#     def run_e(self,miles):
#         """
#         :param miles: 骑行的总里程数
#         :return:
#         """
#         # 通过电量骑行的里程数
#         vol_miles=self.volume*10
#         if vol_miles>= miles:
#             # 当自动骑行里程数大于等于总里程数
#             print(f"自动骑行了{miles}")
#         else:
#             # 当自动骑行里程数小于总里程数
#             print(f"自动骑行了{vol_miles}公里")
#             print(f"脚踩了{miles-vol_miles}公里")
#             super().run(miles-vol_miles)
#
# ebike=EBike()
# ebike.run_e(1000)

# 实战2
# 一个回合制游戏，有两个英雄，分别以两个类进行定义，分别是EZ和JINX
# 每个英雄都有ph属性和power属性，分别代表血量和攻击力
# JINX：ph,1000; power,210
# EZ：ph,1100; power,190
# 每个英雄都有一个figth方法：
   # hero_final_hp=hero_hp-enemy_power
   # enemy_final_hp=enemy_hp-hero_power
   # 对比hero_final_hp和enemy_final_hp

# class Hero:
#     hero_hp=0
#     hero_power=0
#     hero_name=""
#     def figth(self,enemy_hp,enemy_power):
#         """
#         :param enemy_hp: 敌人的血量
#         :param enemy_power: 敌人的攻击力
#         :return:
#         """
#         # 英雄的最后血量
#         hero_final_hp = self.hero_hp - enemy_power
#         # 敌人的最后血量
#         enemy_final_hp = enemy_hp - self.hero_power
#         # 判断谁赢了
#         if hero_final_hp>enemy_final_hp:
#             print(f"{self.hero_name}赢了")
#         elif hero_final_hp<enemy_final_hp:
#             print("敌人赢了")
#         else:
#             print("平局赢了")
# class Jinx(Hero):
#     hero_hp = 1200
#     enemy_power = 210
#     hero_name = "Jinx"
# class Ez(Hero):
#     hero_hp = 1000
#     enemy_power = 190
#     hero_name = "Ez"
# jinx=Jinx()
# jinx.figth(Ez.hero_hp,Ez.enemy_power)
# ez=Ez()
# ez.figth(Jinx.hero_hp,Jinx.enemy_power)